package com.vipheyue.huaxue.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.vipheyue.huaxue.R;
import com.vipheyue.huaxue.activity.DetailActivity;
import com.vipheyue.huaxue.activity.ReleaseActivity;
import com.vipheyue.huaxue.bean.ThingBean;
import com.vipheyue.huaxue.utils.GsonUtils;
import com.vipheyue.huaxue.view.CommonAdapter;
import com.vipheyue.huaxue.view.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

public class ReNameFragment0 extends Fragment {


    @Bind(R.id.pull_refresh_list)
    PullToRefreshListView pull_refresh_list;
    @Bind(R.id.btn_fragment0_search)
    Button btn_fragment0_search;
    @Bind(R.id.btn_fragment0_release)
    Button btn_fragment0_release;
    @Bind(R.id.et_fragment0_searchName)
    EditText et_fragment0_searchName;
    @Bind(R.id.iv_Menu_leftImg)
    ImageView iv_Menu_leftImg;
    @Bind(R.id.tv_Menu_leftTitle)
    TextView tv_Menu_leftTitle;
    @Bind(R.id.rl_menu_left)
    RelativeLayout rl_menu_left;
    @Bind(R.id.tv_Menu_Title)
    TextView tv_Menu_Title;
    @Bind(R.id.iv_menu_rightTitle)
    TextView iv_menu_rightTitle;
    @Bind(R.id.iv_menu_right)
    ImageView iv_menu_right;
    @Bind(R.id.rl_menu_right)
    RelativeLayout rl_menu_right;
    private CommonAdapter<ThingBean> mAdapter;
    private List<ThingBean> mDatas = new ArrayList<ThingBean>();
    private int nowPageNum = 0;
    private int pageSize = 50;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_re_name_fragment0, container, false);
        ButterKnife.bind(this, view);
        initRefresh();
        setAdapter();
        initData(0);
        return view;
    }

    private void initRefresh() {
        rl_menu_left.setVisibility(View.INVISIBLE);
        tv_Menu_Title.setText("APP");
        pull_refresh_list.setMode(PullToRefreshBase.Mode.BOTH);
        pull_refresh_list.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                mDatas.clear();
                nowPageNum = 0;
                initData(nowPageNum);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                // Update the LastUpdatedLabel
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                // Do work to refresh the list here.
                initData(nowPageNum);
            }

        });
    }

    private void setAdapter() {
        //mdatas 记得加数据进去
        mAdapter = new CommonAdapter<ThingBean>(getActivity(), mDatas, R.layout.job_item) {
            @Override
            public void convert(ViewHolder helper, int position, ThingBean item) {
                helper.setText(R.id.tv_fragment0Item_name, item.getName());
            }
        };
        pull_refresh_list.setOnItemClickListener(new ItemClickListener());
        pull_refresh_list.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.btn_fragment0_search, R.id.btn_fragment0_release})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_fragment0_search:
                mDatas.clear();
                nowPageNum = 0;
                initData(nowPageNum);

                break;
            case R.id.btn_fragment0_release:
                startActivity(new Intent(getActivity(), ReleaseActivity.class));
                break;
        }
    }

    private void addCondition(BmobQuery<ThingBean> query) {
        if (!TextUtils.isEmpty(et_fragment0_searchName.getText().toString().trim())) {
            query.addWhereEqualTo("name", et_fragment0_searchName.getText().toString().trim());
        }
    }

    private final class ItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ListView listView = (ListView) parent;
            ThingBean job = (ThingBean) listView.getItemAtPosition(position);
            String jobStr = GsonUtils.toJson(job);
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("jobStr", jobStr);
            startActivity(intent);
        }
    }

    private void initData(int getNumPage) {
        BmobQuery<ThingBean> query = new BmobQuery<ThingBean>();
        query.setLimit(pageSize); // 限制最多10条数据结果作为一页
        query.setSkip(pageSize * getNumPage); // 忽略前10条数据（即第一页数据结果）
        query.order("-updatedAt");
        addCondition(query);
        query.findObjects(getActivity(), new FindListener<ThingBean>() {
            @Override
            public void onSuccess(List<ThingBean> object) {
                mDatas.addAll(object);
                nowPageNum = nowPageNum + 1;
                mAdapter.notifyDataSetChanged();
                // Call onRefreshComplete when the list has been refreshed.
                if (pull_refresh_list != null) {
                    pull_refresh_list.onRefreshComplete();
                }
            }

            @Override
            public void onError(int code, String msg) {
                if (pull_refresh_list != null) {
                    pull_refresh_list.onRefreshComplete();
                }

            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
